<template>
  <el-dialog 
    v-model="dialogVisible" 
    :title="dialogTitle" 
    width="800px"
    class="form-dialog"
    :before-close="handleClose"
  >
    <el-form 
      ref="formRef" 
      :model="form" 
      :rules="rules" 
      label-width="100px"
      label-position="right"
    >
      <!-- 第一行：登录账号和姓名 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="登录账号" prop="username" required>
            <el-input v-model="form.username" placeholder="请输入登录账号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="realName" required>
            <el-input v-model="form.realName" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 第二行：角色类型和角色名称 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="角色类型" prop="roleType" required>
            <el-select 
              v-model="form.roleType" 
              placeholder="请选择角色类型" 
              @change="handleRoleTypeChange" 
              style="width: 100%"
            >
              <el-option label="系统用户" value="system" />
              <el-option label="非系统用户" value="non-system" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色名称" prop="roleName" required>
            <el-input v-model="form.roleName" placeholder="请输入角色名称" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 第三行：出生日期和性别 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birthDate" required>
            <el-date-picker
              v-model="form.birthDate"
              type="datetime"
              placeholder="选择日期时间"
              style="width: 100%"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender" required>
            <el-radio-group v-model="form.gender">
              <el-radio label="male">男</el-radio>
              <el-radio label="female">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 第四行：状态和手机号 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="状态" prop="status" required>
            <el-radio-group v-model="form.status">
              <el-radio label="normal">正常</el-radio>
              <el-radio label="disabled">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 第五行：邮箱和组织机构 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="组织机构" prop="organization">
            <el-select v-model="form.organization" placeholder="请选择组织机构" style="width: 100%">
              <el-option label="大学" value="university" />
              <el-option label="中学" value="middle-school" />
              <el-option label="小学" value="primary-school" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['submit', 'cancel'])

const dialogVisible = ref(false)
const formRef = ref()
const isEdit = ref(false)

// 表单数据
const form = reactive({
  username: '',
  realName: '',
  roleType: '',
  roleName: '',
  birthDate: '',
  gender: 'male',
  status: 'normal',
  phone: '',
  email: '',
  organization: ''
})

// 验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入登录账号', trigger: ['blur', 'change'] },
    {
      pattern: /^[A-Za-z0-9`~!@#$%^&*()_\-+={}[\]|\\:;"'<>,.?/]*$/,
      message: '只能输入数字、英文和特殊字符，不能有空格',
      trigger: ['blur', 'change'],
    },
  ],
  realName: [{ required: true, message: '请输入姓名', trigger: ['blur', 'change'] }],
  roleType: [{ required: true, message: '请选择角色类型', trigger: ['blur', 'change'] }],
  roleName: [{ required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }],
  birthDate: [{ required: true, message: '请选择出生日期', trigger: ['blur', 'change'] }],
  gender: [{ required: true, message: '请选择性别', trigger: ['blur', 'change'] }],
  status: [{ required: true, message: '请选择状态', trigger: ['blur', 'change'] }],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: ['blur', 'change'],
    },
  ],
  email: [
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change'],
    },
  ]
})

// 计算对话框标题
const dialogTitle = computed(() => {
  return isEdit.value ? '编辑用户' : '新增用户'
})

// 角色类型改变时清空角色名称
const handleRoleTypeChange = () => {
  form.roleName = ''
}

// 打开对话框
const openDialog = (userData = null) => {
  // 重置表单
  Object.keys(form).forEach(key => {
    form[key] = ''
  })
  
  // 设置默认值
  form.gender = 'male'
  form.status = 'normal'
  
  // 如果是编辑模式，填充数据
  if (userData) {
    isEdit.value = true
    Object.assign(form, userData)
  } else {
    isEdit.value = false
  }
  
  dialogVisible.value = true
  
  // 清除验证状态
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  })
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 取消操作
const handleCancel = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  dialogVisible.value = false
  emit('cancel')
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 验证表单
    const valid = await formRef.value.validate()
    if (valid) {
      // 提交逻辑
      console.log('表单数据:', form)
      ElMessage.success(isEdit.value ? '用户信息更新成功' : '用户信息添加成功')
      dialogVisible.value = false
      emit('submit', { ...form })
    }
  } catch (error) {
    console.log('表单验证失败:', error)
  }
}

// 暴露方法给父组件
defineExpose({
  openDialog
})
</script>

<style scoped>
.form-dialog {
  width: 800px;
}
.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
:deep(.el-form-item) {
  margin-bottom: 18px;
}
</style>